package com.java1412.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.java1412.utils.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 验证后台没有登录无法访问某些接口
 *
 * @author java1412
 * @since 2023-06-25 15:50:01
 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    // 调用控制器之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 对token进行校验
        String token = request.getHeader("token");
        // 判断token是否为空，如果为空，表示没有登录,登录接口除外
        System.out.println(token);
        if (ObjectUtils.isEmpty(token)) {
            // token是空的
            // 以json的形式向前端返回状态
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            ResponseUtil r = ResponseUtil.createR(401, "未授权");
            ObjectMapper om = new ObjectMapper();
            String json = om.writeValueAsString(r);
            writer.write(json);
            writer.flush();
            return false; // 不放行
        } else {
            // token不是空的，就需要放行
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
